'use strict';

define(['modules/app'], function(jfApp) {

  jfApp.controller('searchCtrl', ['$scope', '$http', '$location', '$window', '$cookies','$timeout',
    function($scope, $http, $location, $window, $cookies, $timeout) {
    	$scope.params = {
    		search : $location.search().search
    	}

        loadHotSearch();

        $scope.recentSearch = $cookies.get("recentSearch") ? $cookies.get("recentSearch").split(",") : [];

        function loadHotSearch(){
            $http.get("index.php?route=feed/rest_api/hotSearch").then(
              function(result) {
                if (result.data.success) {
                  var filters = result.data.data;
                  if(filters){
                    var len = filters.length;
                    var index = parseInt(Math.random()*len)-1;
                    index = index < 0 ? 0 : index;
                    $scope.filters = filters[index];
                  }
                }
              }
            )
        }

        $scope.refresh = function(){
            loadHotSearch();
        }
        $scope.$on('$viewContentLoaded', function() {
            $timeout(function(){
                $('#inputTxtSub').focus();
            },400);
        });    

        $scope.search = function(){
            $cookies.remove('products_page', { path: '/' });
            // if(!$scope.params.search){
            //     BHZ.MessageDialog.show("请输入关键字","知道了");
            //     return;
            // }
            if($scope.params.search){
                if($scope.recentSearch.indexOf($scope.params.search) == -1){
                    $scope.recentSearch.push($scope.params.search);
                    $cookies.put("recentSearch",$scope.recentSearch.toString())
                }
            }
            $location.search({"search":$scope.params.search});
            $location.path("/products");
        }

    	$scope.back = function(){
    		$window.history.back();
    	}

        $scope.clearRecent = function(){
            $cookies.put("recentSearch","");
            $scope.recentSearch = new Array();
        }
  }])

});